/**
 * 性能监控工具
 * 实时监控系统性能指标和资源使用情况
 */

import { performance } from 'perf_hooks'
import os from 'os'
import fs from 'fs/promises'
import path from 'path'
import { EventEmitter } from 'events'

class PerformanceMonitor extends EventEmitter {
  constructor(options = {}) {
    super()

    this.options = {
      interval: options.interval || 5000, // 5秒间隔
      logFile: options.logFile || 'performance_metrics.log',
      maxHistory: options.maxHistory || 1000,
      enableAPM: options.enableAPM || false,
      ...options
    }

    this.isMonitoring = false
    this.metrics = []
    this.startTime = Date.now()
    this.monitoringInterval = null

    // 系统信息
    this.systemInfo = {
      platform: os.platform(),
      arch: os.arch(),
      totalMemory: os.totalmem(),
      cpuCount: os.cpus().length,
      hostname: os.hostname()
    }

    // 性能基准
    this.benchmarks = {
      responseTime: {
        good: 500,    // < 500ms
        fair: 1000,   // < 1000ms
        poor: 3000    // < 3000ms
      },
      cpuUsage: {
        good: 50,     // < 50%
        fair: 75,     // < 75%
        poor: 90      // < 90%
      },
      memoryUsage: {
        good: 70,     // < 70%
        fair: 85,     // < 85%
        poor: 95      // < 95%
      },
      errorRate: {
        good: 1,      // < 1%
        fair: 5,      // < 5%
        poor: 10      // < 10%
      }
    }
  }

  /**
   * 开始监控
   */
  start() {
    if (this.isMonitoring) {
      console.warn('⚠️ 性能监控已在运行')
      return
    }

    console.log('🚀 启动性能监控...')
    this.isMonitoring = true
    this.startTime = Date.now()

    // 立即收集一次指标
    this.collectMetrics()

    // 定期收集指标
    this.monitoringInterval = setInterval(() => {
      this.collectMetrics()
    }, this.options.interval)

    // 监听进程退出事件
    process.on('SIGINT', () => this.stop())
    process.on('SIGTERM', () => this.stop())

    this.emit('started')
  }

  /**
   * 停止监控
   */
  stop() {
    if (!this.isMonitoring) {
      return
    }

    console.log('🛑 停止性能监控...')
    this.isMonitoring = false

    if (this.monitoringInterval) {
      clearInterval(this.monitoringInterval)
      this.monitoringInterval = null
    }

    // 生成最终报告
    this.generateFinalReport()

    this.emit('stopped')
  }

  /**
   * 收集性能指标
   */
  collectMetrics() {
    const timestamp = Date.now()

    // 系统指标
    const systemMetrics = this.getSystemMetrics()

    // 进程指标
    const processMetrics = this.getProcessMetrics()

    // 应用指标
    const applicationMetrics = this.getApplicationMetrics()

    const metrics = {
      timestamp,
      uptime: Date.now() - this.startTime,
      system: systemMetrics,
      process: processMetrics,
      application: applicationMetrics,
      performance: this.calculatePerformanceScore(systemMetrics, processMetrics, applicationMetrics)
    }

    // 存储指标
    this.metrics.push(metrics)

    // 限制历史记录数量
    if (this.metrics.length > this.options.maxHistory) {
      this.metrics.shift()
    }

    // 记录到日志
    this.logMetrics(metrics)

    // 检查性能告警
    this.checkPerformanceAlerts(metrics)

    // 发出指标事件
    this.emit('metrics', metrics)
  }

  /**
   * 获取系统指标
   */
  getSystemMetrics() {
    const cpus = os.cpus()
    const loadAvg = os.loadavg()
    const totalMemory = os.totalmem()
    const freeMemory = os.freemem()
    const usedMemory = totalMemory - freeMemory

    // CPU使用率（简化计算）
    const cpuUsage = this.calculateCPUUsage(cpus)

    return {
      cpu: {
        usage: cpuUsage,
        loadAverage: loadAvg,
        coreCount: cpus.length,
        model: cpus[0]?.model || 'Unknown'
      },
      memory: {
        total: totalMemory,
        used: usedMemory,
        free: freeMemory,
        usagePercent: (usedMemory / totalMemory) * 100,
        available: freeMemory
      },
      network: {
        interfaces: this.getNetworkInterfaces()
      },
      disk: {
        // 这里可以添加磁盘使用情况
        total: 0,
        used: 0,
        free: 0
      }
    }
  }

  /**
   * 获取进程指标
   */
  getProcessMetrics() {
    const memUsage = process.memoryUsage()
    const cpuUsage = process.cpuUsage()

    return {
      pid: process.pid,
      uptime: process.uptime(),
      memory: {
        rss: memUsage.rss,
        heapTotal: memUsage.heapTotal,
        heapUsed: memUsage.heapUsed,
        external: memUsage.external,
        arrayBuffers: memUsage.arrayBuffers
      },
      cpu: {
        user: cpuUsage.user,
        system: cpuUsage.system
      },
      eventLoop: this.getEventLoopMetrics()
    }
  }

  /**
   * 获取应用指标
   */
  getApplicationMetrics() {
    // 这里应该从实际应用中获取指标
    // 暂时返回模拟数据
    return {
      http: {
        requests: this.getHttpRequestMetrics(),
        responseTime: this.getAverageResponseTime(),
        errorRate: this.getErrorRate()
      },
      database: {
        connections: this.getDatabaseConnections(),
        queryTime: this.getAverageQueryTime(),
        errors: this.getDatabaseErrors()
      },
      ai: {
        inferenceTime: this.getInferenceTimeMetrics(),
        modelMemory: this.getModelMemoryUsage(),
        queueSize: this.getAIQueueSize()
      },
      custom: this.getCustomMetrics()
    }
  }

  /**
   * 计算CPU使用率
   */
  calculateCPUUsage(cpus) {
    let totalIdle = 0
    let totalTick = 0

    cpus.forEach(cpu => {
      for (const type in cpu.times) {
        totalTick += cpu.times[type]
      }
      totalIdle += cpu.times.idle
    })

    return 100 - (totalIdle / totalTick) * 100
  }

  /**
   * 获取网络接口信息
   */
  getNetworkInterfaces() {
    const interfaces = os.networkInterfaces()
    const result = {}

    for (const [name, addrs] of Object.entries(interfaces)) {
      result[name] = addrs.map(addr => ({
        family: addr.family,
        address: addr.address,
        netmask: addr.netmask,
        internal: addr.internal,
        mac: addr.mac
      }))
    }

    return result
  }

  /**
   * 获取事件循环指标
   */
  getEventLoopMetrics() {
    const start = process.hrtime.bigint()
    setImmediate(() => {
      const delay = Number(process.hrtime.bigint() - start) / 1000000 // 转换为毫秒
      return { lag: delay }
    })

    return { lag: 0 } // 简化实现
  }

  /**
   * 获取HTTP请求指标（模拟）
   */
  getHttpRequestMetrics() {
    return {
      total: Math.floor(Math.random() * 1000) + 500,
      active: Math.floor(Math.random() * 50) + 10,
      completed: Math.floor(Math.random() * 950) + 450,
      errors: Math.floor(Math.random() * 10)
    }
  }

  /**
   * 获取平均响应时间（模拟）
   */
  getAverageResponseTime() {
    return Math.random() * 1000 + 100 // 100-1100ms
  }

  /**
   * 获取错误率（模拟）
   */
  getErrorRate() {
    return Math.random() * 5 // 0-5%
  }

  /**
   * 获取数据库连接数（模拟）
   */
  getDatabaseConnections() {
    return Math.floor(Math.random() * 20) + 5
  }

  /**
   * 获取平均查询时间（模拟）
   */
  getAverageQueryTime() {
    return Math.random() * 100 + 10 // 10-110ms
  }

  /**
   * 获取数据库错误数（模拟）
   */
  getDatabaseErrors() {
    return Math.floor(Math.random() * 5)
  }

  /**
   * 获取AI推理时间指标（模拟）
   */
  getInferenceTimeMetrics() {
    return {
      average: Math.random() * 2000 + 1000, // 1-3秒
      min: Math.random() * 500 + 500,        // 0.5-1秒
      max: Math.random() * 1000 + 3000        // 3-4秒
    }
  }

  /**
   * 获取模型内存使用（模拟）
   */
  getModelMemoryUsage() {
    return Math.random() * 1024 * 1024 * 1024 + 512 * 1024 * 1024 // 512MB-1.5GB
  }

  /**
   * 获取AI队列大小（模拟）
   */
  getAIQueueSize() {
    return Math.floor(Math.random() * 100)
  }

  /**
   * 获取自定义指标
   */
  getCustomMetrics() {
    return {
      // 这里可以添加应用特定的自定义指标
      activeUsers: Math.floor(Math.random() * 100) + 20,
      queuedTasks: Math.floor(Math.random() * 50) + 10,
      cacheHitRate: Math.random() * 100
    }
  }

  /**
   * 计算性能评分
   */
  calculatePerformanceScore(systemMetrics, processMetrics, applicationMetrics) {
    let score = 100

    // CPU评分
    if (systemMetrics.cpu.usage > this.benchmarks.cpuUsage.poor) {
      score -= 30
    } else if (systemMetrics.cpu.usage > this.benchmarks.cpuUsage.fair) {
      score -= 15
    }

    // 内存评分
    if (systemMetrics.memory.usagePercent > this.benchmarks.memoryUsage.poor) {
      score -= 30
    } else if (systemMetrics.memory.usagePercent > this.benchmarks.memoryUsage.fair) {
      score -= 15
    }

    // 响应时间评分
    if (applicationMetrics.http.responseTime > this.benchmarks.responseTime.poor) {
      score -= 25
    } else if (applicationMetrics.http.responseTime > this.benchmarks.responseTime.fair) {
      score -= 10
    }

    // 错误率评分
    if (applicationMetrics.http.errorRate > this.benchmarks.errorRate.poor) {
      score -= 20
    } else if (applicationMetrics.http.errorRate > this.benchmarks.errorRate.fair) {
      score -= 5
    }

    return Math.max(0, score)
  }

  /**
   * 记录指标到日志
   */
  async logMetrics(metrics) {
    const logEntry = {
      timestamp: new Date(metrics.timestamp).toISOString(),
      performance: metrics.performance,
      cpu: metrics.system.cpu.usage.toFixed(2),
      memory: metrics.system.memory.usagePercent.toFixed(2),
      responseTime: metrics.application.http.responseTime.toFixed(2),
      errorRate: metrics.application.http.errorRate.toFixed(2)
    }

    try {
      await fs.appendFile(
        this.options.logFile,
        JSON.stringify(logEntry) + '\n'
      )
    } catch (error) {
      console.error('❌ 写入性能日志失败:', error.message)
    }
  }

  /**
   * 检查性能告警
   */
  checkPerformanceAlerts(metrics) {
    const alerts = []

    // CPU告警
    if (metrics.system.cpu.usage > this.benchmarks.cpuUsage.poor) {
      alerts.push({
        type: 'CPU_HIGH',
        severity: 'CRITICAL',
        message: `CPU使用率过高: ${metrics.system.cpu.usage.toFixed(2)}%`,
        value: metrics.system.cpu.usage
      })
    }

    // 内存告警
    if (metrics.system.memory.usagePercent > this.benchmarks.memoryUsage.poor) {
      alerts.push({
        type: 'MEMORY_HIGH',
        severity: 'CRITICAL',
        message: `内存使用率过高: ${metrics.system.memory.usagePercent.toFixed(2)}%`,
        value: metrics.system.memory.usagePercent
      })
    }

    // 响应时间告警
    if (metrics.application.http.responseTime > this.benchmarks.responseTime.poor) {
      alerts.push({
        type: 'RESPONSE_TIME_HIGH',
        severity: 'WARNING',
        message: `响应时间过长: ${metrics.application.http.responseTime.toFixed(2)}ms`,
        value: metrics.application.http.responseTime
      })
    }

    // 错误率告警
    if (metrics.application.http.errorRate > this.benchmarks.errorRate.poor) {
      alerts.push({
        type: 'ERROR_RATE_HIGH',
        severity: 'CRITICAL',
        message: `错误率过高: ${metrics.application.http.errorRate.toFixed(2)}%`,
        value: metrics.application.http.errorRate
      })
    }

    // 发出告警事件
    if (alerts.length > 0) {
      alerts.forEach(alert => {
        console.warn(`🚨 ${alert.severity}: ${alert.message}`)
        this.emit('alert', alert)
      })
    }
  }

  /**
   * 生成最终报告
   */
  generateFinalReport() {
    if (this.metrics.length === 0) {
      console.log('📊 没有性能数据可生成报告')
      return
    }

    const report = {
      summary: this.generateSummary(),
      details: this.generateDetailedReport(),
      recommendations: this.generateRecommendations()
    }

    // 保存报告
    this.saveReport(report)

    // 输出报告摘要
    console.log('\n📊 性能监控报告')
    console.log('================')
    console.log(`监控时长: ${(report.summary.duration / 1000 / 60).toFixed(2)} 分钟`)
    console.log(`平均性能评分: ${report.summary.averagePerformance.toFixed(2)}`)
    console.log(`最大CPU使用率: ${report.summary.maxCPU.toFixed(2)}%`)
    console.log(`最大内存使用率: ${report.summary.maxMemory.toFixed(2)}%`)
    console.log(`平均响应时间: ${report.summary.averageResponseTime.toFixed(2)}ms`)
    console.log(`总错误数: ${report.summary.totalErrors}`)

    return report
  }

  /**
   * 生成摘要
   */
  generateSummary() {
    const duration = Date.now() - this.startTime
    const performanceScores = this.metrics.map(m => m.performance)
    const cpuUsages = this.metrics.map(m => m.system.cpu.usage)
    const memoryUsages = this.metrics.map(m => m.system.memory.usagePercent)
    const responseTimes = this.metrics.map(m => m.application.http.responseTime)
    const errorRates = this.metrics.map(m => m.application.http.errorRate)

    return {
      duration,
      sampleCount: this.metrics.length,
      averagePerformance: performanceScores.reduce((a, b) => a + b, 0) / performanceScores.length,
      maxCPU: Math.max(...cpuUsages),
      avgCPU: cpuUsages.reduce((a, b) => a + b, 0) / cpuUsages.length,
      maxMemory: Math.max(...memoryUsages),
      avgMemory: memoryUsages.reduce((a, b) => a + b, 0) / memoryUsages.length,
      maxResponseTime: Math.max(...responseTimes),
      avgResponseTime: responseTimes.reduce((a, b) => a + b, 0) / responseTimes.length,
      totalErrors: errorRates.reduce((a, b) => a + b, 0)
    }
  }

  /**
   * 生成详细报告
   */
  generateDetailedReport() {
    return {
      systemInfo: this.systemInfo,
      benchmarks: this.benchmarks,
      timeline: this.metrics.map(m => ({
        timestamp: m.timestamp,
        performance: m.performance,
        cpu: m.system.cpu.usage,
        memory: m.system.memory.usagePercent,
        responseTime: m.application.http.responseTime,
        errorRate: m.application.http.errorRate
      }))
    }
  }

  /**
   * 生成优化建议
   */
  generateRecommendations() {
    const recommendations = []
    const summary = this.generateSummary()

    if (summary.avgCPU > this.benchmarks.cpuUsage.fair) {
      recommendations.push({
        category: 'CPU',
        priority: 'HIGH',
        description: 'CPU使用率较高，建议优化算法或增加计算资源'
      })
    }

    if (summary.avgMemory > this.benchmarks.memoryUsage.fair) {
      recommendations.push({
        category: 'MEMORY',
        priority: 'HIGH',
        description: '内存使用率较高，建议检查内存泄漏或增加内存容量'
      })
    }

    if (summary.avgResponseTime > this.benchmarks.responseTime.fair) {
      recommendations.push({
        category: 'RESPONSE_TIME',
        priority: 'MEDIUM',
        description: '响应时间较长，建议优化数据库查询和API处理逻辑'
      })
    }

    if (summary.totalErrors > 0) {
      recommendations.push({
        category: 'ERRORS',
        priority: 'HIGH',
        description: '检测到错误，建议加强错误处理和监控'
      })
    }

    if (recommendations.length === 0) {
      recommendations.push({
        category: 'GENERAL',
        priority: 'INFO',
        description: '系统性能良好，继续保持当前配置'
      })
    }

    return recommendations
  }

  /**
   * 保存报告
   */
  async saveReport(report) {
    const reportFile = `performance_report_${Date.now()}.json`

    try {
      await fs.writeFile(
        reportFile,
        JSON.stringify(report, null, 2)
      )
      console.log(`📄 性能报告已保存到: ${reportFile}`)
    } catch (error) {
      console.error('❌ 保存性能报告失败:', error.message)
    }
  }

  /**
   * 获取实时指标
   */
  getCurrentMetrics() {
    return this.metrics[this.metrics.length - 1] || null
  }

  /**
   * 获取历史指标
   */
  getHistoricalMetrics(limit = 100) {
    return this.metrics.slice(-limit)
  }

  /**
   * 获取性能趋势
   */
  getPerformanceTrends(minutes = 60) {
    const cutoff = Date.now() - (minutes * 60 * 1000)
    return this.metrics.filter(m => m.timestamp >= cutoff)
  }
}

export default PerformanceMonitor

// 如果直接运行此文件
if (import.meta.url === `file://${process.argv[1]}`) {
  const monitor = new PerformanceMonitor({
    interval: 5000,
    logFile: 'performance_monitor.log'
  })

  // 监听事件
  monitor.on('started', () => {
    console.log('✅ 性能监控已启动')
  })

  monitor.on('metrics', (metrics) => {
    if (metrics.performance < 70) {
      console.warn(`⚠️ 性能评分较低: ${metrics.performance.toFixed(2)}`)
    }
  })

  monitor.on('alert', (alert) => {
    console.error(`🚨 ${alert.severity}告警: ${alert.message}`)
  })

  monitor.on('stopped', () => {
    console.log('✅ 性能监控已停止')
    process.exit(0)
  })

  // 启动监控
  monitor.start()

  // 优雅关闭
  process.on('SIGINT', () => {
    console.log('\n正在停止性能监控...')
    monitor.stop()
  })
}